<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 广告信息管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container v2-group">
            <div class="bulletin">
                <el-popover
                    placement="bottom"
                    trigger="hover">
                    <div class="pop-content statistics">
                        <div>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                :value="statistics.price"
                                title="总金额"
                            ></el-statistic>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                :value="statistics.finished_price"
                                title="已完成广告金额"
                            ></el-statistic>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                :value="statistics.online_price"
                                title="进行中广告金额"
                            ></el-statistic>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                :value="statistics.not_start_price"
                                title="未开始广告金额"
                            ></el-statistic>
                        </div>
                    </div>
                    <el-row slot="reference" :gutter="20"
                        v-loading="loading"
                        >
                        <el-col :span="6">
                            <div>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                :value="statistics.total"
                                title="广告总数"
                            ></el-statistic>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                decimal-separator="."
                                :value="statistics.finished_total"
                                title="已完成广告数量"
                            >
                            </el-statistic>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                decimal-separator="."
                                :value="statistics.online_total"
                                title="进行中广告数量"
                            >
                            </el-statistic>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div>
                            <el-statistic
                                group-separator=","
                                :precision="0"
                                decimal-separator="."
                                :value="statistics.not_start_total"
                                title="未开始广告数量"
                            >
                            </el-statistic>
                            </div>
                        </el-col>
                    </el-row>
                </el-popover>
            </div>
            <div class="handle-box">
                <el-date-picker
                    v-model="query.start"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="开始时间">
                </el-date-picker>
                <el-date-picker
                    v-model="query.end"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="结束时间">
                </el-date-picker>
                <el-input v-model="query.kw" placeholder="关键词" class="handle-input mr10" clearable></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                <el-button
                    type="success"
                    icon="el-icon-plus"
                    class="handle-del mr10"
                    @click="handleAdd"
                >新增广告信息</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                stripe
            >
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column prop="content" label="内容"></el-table-column>
                <el-table-column prop="tar" label="投放目标"></el-table-column>
                <el-table-column prop="manager" label="管理人"></el-table-column>
                <el-table-column label="开始时间">
                    <template slot-scope="scope">{{scope.row.start_time}}</template>
                </el-table-column>
                <el-table-column label="结束时间">
                    <template slot-scope="scope">{{scope.row.end_time}}</template>
                </el-table-column>
                <el-table-column label="操作" width="210">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="query.page"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="entityEdit" :model="form" :rules="rulesEntityEdit" label-width="100px"
            v-loading="loading">
                <el-form-item label="来源" prop="source">
                    <el-input v-model="form.source"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="ad_unit">
                    <el-input v-model="form.ad_unit"></el-input>
                </el-form-item>
                <el-form-item label="广告类型" prop="ad_type">
                    <el-input v-model="form.ad_type"></el-input>
                </el-form-item>
                <el-form-item label="投放目标" prop="tar">
                    <el-select v-model="form.tar" placeholder="- 投放目标 -" clearable @change="handleTargetChange">
                        <el-option v-for="item in listTarget" :key="item.label" :label="item.name" :value="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item> 
                <el-form-item label="内容" prop="content">
                    <el-input v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="图片文件" prop="img_list">
                    <span
                        class="media-list"
                        v-for="(item, index) in img_list"
                        :key="index"
                    >
                        <el-image 
                            style="width: 100px; height: 100px"
                            :src="item" 
                            :preview-src-list="img_list">
                        </el-image>
                        <i class="el-icon-error" @click="handleImageDelete(item, index)"></i>
                    </span>
                </el-form-item>
                <el-form-item label="视频文件" prop="video_list">
                    <span
                        class="media-list"
                        v-for="(item, index) in video_list"
                        :key="index"
                    >
                        <video controls width="250">
                            <source :src="item" type="video/mp4" />
                            下载
                            <a :href="item">MP4</a>
                            视频。
                        </video>
                        <i class="el-icon-error" @click="handleVideoDelete(item, index)"></i>
                    </span>
                </el-form-item>
                <el-form-item label="上传图片文件" width="100px" prop="file">
                    <el-upload
                        class="upload-demo"
                        drag
                        ref="uploadImage"
                        :auto-upload="false"
                        :on-change="handleFileChangeImage"
                        action=""
                        :limite="1"
                        :multiple="false">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传文件不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="上传视频文件" width="100px" prop="file">
                    <el-upload
                        class="upload-demo"
                        drag
                        ref="uploadVideo"
                        :auto-upload="false"
                        :on-change="handleFileChangeVideo"
                        action=""
                        :limite="1"
                        :multiple="false">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传文件不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="金额" prop="price">
                    <el-input v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="contact">
                    <el-input v-model="form.contact"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="tel">
                    <el-input v-model="form.tel"></el-input>
                </el-form-item>
                <el-form-item label="管理人" prop="manager">
                    <el-input v-model="form.manager"></el-input>
                </el-form-item>
                <el-form-item label="开始时间" prop="start_time">
                    <el-date-picker
                        v-model="form.start_time"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="end_time">
                    <el-date-picker
                        v-model="form.end_time"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="entityAdd" :model="form" :rules="rulesEntityAdd" label-width="100px"
            v-loading="loading">
                <el-form-item label="来源" prop="source">
                    <el-input v-model="form.source"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="ad_unit">
                    <el-input v-model="form.ad_unit"></el-input>
                </el-form-item>
                <el-form-item label="广告类型" prop="ad_type">
                    <el-input v-model="form.ad_type"></el-input>
                </el-form-item>
                <el-form-item label="投放目标" prop="tar">
                    <el-select v-model="form.tar" placeholder="- 投放目标 -" clearable @change="handleTargetChange">
                        <el-option v-for="item in listTarget" :key="item.label" :label="item.name" :value="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item> 
                <el-form-item label="内容" prop="content">
                    <el-input v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="上传图片文件" width="100px" prop="file">
                    <el-upload
                        class="upload-demo"
                        drag
                        ref="uploadImage"
                        :auto-upload="false"
                        :on-change="handleFileChangeImage"
                        action=""
                        :limite="1"
                        :multiple="false">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传文件不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="上传视频文件" width="100px" prop="file">
                    <el-upload
                        class="upload-demo"
                        drag
                        ref="uploadVideo"
                        :auto-upload="false"
                        :on-change="handleFileChangeVideo"
                        action=""
                        :limite="1"
                        :multiple="false">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传文件不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="金额" prop="price">
                    <el-input v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="contact">
                    <el-input v-model="form.contact"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="tel">
                    <el-input v-model="form.tel"></el-input>
                </el-form-item>
                <el-form-item label="管理人" prop="manager">
                    <el-input v-model="form.manager"></el-input>
                </el-form-item>
                <el-form-item label="开始时间" prop="start_time">
                    <el-date-picker
                        v-model="form.start_time"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="end_time">
                    <el-date-picker
                        v-model="form.end_time"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import api from '../../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                start: '',
                end: '',
                ad_type: '',
                kw: '',
                page: 1,
                size: 10
            },
            tableData: [
                {
                    username: 'user01',
                    surname: '张三',
                    user_group: '普通用户',
                    last_login: '2024-11-01 00:00:00',
                    status: '正常'
                }
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addVisible: false,
            roles: [],
            rulesEntityAdd: {
                source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
                ad_unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
                ad_type: [{ required: true, message: '请输入广告类型', trigger: 'blur' }],
                tar:  [{ required: true, message: '请选择投放目标', trigger: 'change', type: 'string' }],
                title: [{ required: true, message: '请输入内容', trigger: 'blur' }],
                content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
                price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
                contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
                tel: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
                manager: [{ required: true, message: '请输入管理人', trigger: 'blur' }],
                start_time:  [{ required: true, message: '请选择开始时间', trigger: 'change', type: 'string' }],
                end_time:  [{ required: true, message: '请选择结束时间', trigger: 'change', type: 'string' }]
            },
            rulesEntityEdit: {
                source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
                ad_unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
                ad_type: [{ required: true, message: '请输入广告类型', trigger: 'blur' }],
                tar:  [{ required: true, message: '请选择投放目标', trigger: 'change', type: 'string' }],
                title: [{ required: true, message: '请输入内容', trigger: 'blur' }],
                content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
                price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
                contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
                tel: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
                manager: [{ required: true, message: '请输入管理人', trigger: 'blur' }],
                start_time:  [{ required: true, message: '请选择开始时间', trigger: 'change', type: 'string' }],
                end_time:  [{ required: true, message: '请选择结束时间', trigger: 'change', type: 'string' }]
            },
            statistics: {
                crawlerNum: 12,
                todayAlarm: 3,
                todayTotal: 30,
            },
            loading: false,
            listTarget: [],
            img_list: [],
            video_list: []
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            api.getCastList(this.query).then(res => {
                this.tableData = res.items;
                this.pageTotal = res.total;
            }).catch(err => {
                this.$message.error(err);
            });
            api.getCastStatistics({}).then(res => {
                this.statistics = res;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'page', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                api.deleteCast({pk: row.id}).then(res => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(err => {
                    this.$message.error(err);
                });
            })
            .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            var that = this;
            that.idx = index;
            that.form = Object.assign({}, row);

            api.getCastDetail({pk: this.form.id}).then(res => {
                that.form = res.item;
                if (that.form.img_list) {
                    that.form.img_list = that.form.img_list.map(m => m.url);
                }
                if (that.form.video_list) {
                    that.form.video_list = that.form.video_list.map(m => m.url);
                }
                if (that.form.imgs) {
                    that.form.img_list = that.form.imgs.map(m => m.url);
                    that.img_list = that.form.img_list;
                }
                if (that.form.video) {
                    that.form.video_list = that.form.video.map(m => m.url);
                    that.video_list = that.form.video_list;
                }
            }).catch(err => {
                that.$message.error(err);
            });

            that.editVisible = true;
            if (that.$refs.uploadImage !== undefined) {
                that.$refs.uploadImage.clearFiles();
            }
            if (that.$refs.uploadVideo !== undefined) {
                that.$refs.uploadVideo.clearFiles();
            }
            that.loadTarget();
        },
        // 保存编辑
        saveEdit() {
            this.$refs.entityEdit.validate(valid => {
                if (valid) {
                    this.loading = true;
                    var param = Object.assign({}, this.form, {pk: this.form.id, img_list: JSON.stringify(this.form.img_list ? this.form.img_list : []), video_list: JSON.stringify(this.video_list ? this.video_list : [])});
                    param.imgs = param.imgs ? param.imgs.map(m => m.raw) : [];
                    if (param.imgs.length === 0) {
                        delete param.imgs;
                    }
                    param.videos = param.videos ? param.videos.map(m => m.raw) : [];
                    if (param.videos.length === 0) {
                        delete param.videos;
                    }
                    // param.videos = param.videos[0];
                    delete param.id;
                    delete param.update_time;
                    delete param.image;
                    delete param.video;
                    api.editCast(param).then(res => {
                        this.editVisible = false;
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        this.loading = false;
                        // this.$set(this.tableData, this.idx, this.form);
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                        this.loading = false;
                    });
                } else {
                    return false;
                }
            });
        },
        // 新增操作
        handleAdd() {
            this.form = {};
            this.addVisible = true;
            if (this.$refs.upload !== undefined) {
                this.$refs.upload.clearFiles();
            }
            this.img_list = [];
            this.video_list = [];
            this.loadTarget();
        },
        saveAdd() {
            this.$refs.entityAdd.validate(valid => {
                if (valid) {
                    this.loading = true;
                    var param = Object.assign({}, this.form, {pk: this.form.id, img_list: JSON.stringify(this.form.img_list ? this.form.img_list : []), video_list: JSON.stringify(this.video_list ? this.video_list : [])});
                    param.imgs = param.imgs ? param.imgs.map(m => m.raw) : [];
                    if (param.imgs.length === 0) {
                        delete param.imgs;
                    }
                    param.videos = param.videos ? param.videos.map(m => m.raw) : [];
                    if (param.videos.length === 0) {
                        delete param.videos;
                    }
                    api.addCast(param).then(res => {
                        this.editVisible = false;
                        this.$message.success(`新增成功`);
                        this.addVisible = false;
                        this.loading = false;
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                        this.loading = false;
                    });
                } else {
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'size', val);
            this.getData();
        },
        handleFileChangeImage(file, fileList) {
            this.form.imgs = fileList;
        },
        handleFileChangeVideo(file, fileList) {
            this.form.videos = fileList;
        },
        loadTarget() {
            api.getCastTargetList({
                ad_type: '',
                kw: '',
                page: 1,
                size: 100
            }).then(res => {
                this.listTarget = res.items.map(m => {
                    var n = {
                        label: m.id,
                        name: m.title
                    };
                    return n;
                });
            }).catch(err => {
                this.$message.error(err);
            });
        },
        handleTargetChange(e) {
            if (e) {
                this.form.tar_id = this.listTarget.filter(el => el.name === e)[0].label;
                this.form.tar = e;
            }
            else {
                delete this.form.tar_id;
                delete this.form.tar;
            }
        },
        handleVideoDelete(item, index) {
            this.form.video_list.splice(index, 1);
        },
        handleImageDelete(item, index) {
            this.form.img_list.splice(index, 1);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-dialog .el-date-editor.el-input, .el-dialog .el-select {
    width: 100%;
}
.media-list {
    position: relative;
    display: inline-block;

    .el-icon-error {
        color: #F56C6C;
        position: absolute;
        top: -6px;
        right: 0px;
        font-size: 24px;
        background-color: #fff;
        border-radius: 12px;
    }
}
</style>
